import getopt, sys, os
from xml.dom import minidom

def remove_whitespace_nodes(dom):
    """ 
    This method is called recursively for each element within the submitted dom
    and is used to remove empty whitespace elements
    """
    for child in list( dom.childNodes ):
        if child.nodeType == child.TEXT_NODE and child.data.strip() == '':
            dom.removeChild(child)
        else:
            remove_whitespace_nodes(child)

def domToDict(dom):
    """ 
    This method is called recursively for each element within the dom.
    Depending on the parent type, the return value will either be a dictionary, list, or single value
    """

    remove_whitespace_nodes( dom )

    if dom.nodeType == dom.ELEMENT_NODE and dom.getAttribute('type') == 'array':
        my_stor = []
    else:
        my_stor = {}

    for node in dom.childNodes:
        if len( node.childNodes ):
            if isinstance( my_stor, list ):
                my_stor.append( domToDict( node ) )
            else:
                my_stor[node.nodeName] = domToDict( node )
        else:
            if node.nodeType == node.TEXT_NODE:
                return node.nodeValue
            else:
                if node.hasAttribute('nil'):
                    my_stor[node.nodeName] = None
                else:
                    my_stor[node.nodeName] = node.nodeValue

    return my_stor

class ConfigException( Exception ): pass

class Config( object ):
    
    def __init__(self, config_file, root):
        # verify config file validity
        if not os.path.isfile( config_file ):
            raise ConfigException( 'config file is invalid', '' )
        
        try:
            config_dom = minidom.parse( config_file )
            config_dict = domToDict( config_dom )[root]
        except:
            raise ConfigException( sys.exc_info()[1], '' )
        
        self.config_dict = config_dict

    def getSection(self, section):
        if not section in self.config_dict:
            raise ConfigException( '%s config options not found' % str( section ), '' )

        return self.config_dict[ section ]
    
    def getConfig(self):
        return self.config_dict